########################################################################
#  Searx-Qt - Lightweight desktop application for Searx.
#  Copyright (C) 2020-2022  CYBERDEViL
#
#  This file is part of Searx-Qt.
#
#  Searx-Qt is free software: you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation, either version 3 of the License, or
#  (at your option) any later version.
#
#  Searx-Qt is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program.  If not, see <https://www.gnu.org/licenses/>.
#
########################################################################

from urllib.parse import urlparse

from PyQt5.QtWidgets import (
    QFormLayout,
    QLabel,
    QLineEdit,
    QComboBox,
    QDialog,
    QTextBrowser,
    QVBoxLayout
)

from searxqt.core.http import ErrorTypeStr

from searxqt.widgets.buttons import Button

from searxqt.translations import _


class ErrorMessage(QDialog):
    def __init__(self, error, parent=None):
        QDialog.__init__(self, parent=parent)
        self.setWindowTitle(_("Error"))

        layout = QVBoxLayout(self)
        label = QLabel(_("A error has occured!"), self)
        errorMessage = QTextBrowser(self)
        okButton = Button(_("Ok"), self)

        layout.addWidget(label)
        layout.addWidget(errorMessage)
        layout.addWidget(okButton)

        errorMessage.setPlainText(error)

        okButton.clicked.connect(self.accept)


class RequestsErrorMessage(ErrorMessage):
    def __init__(self, errorType, errorMsg, parent=None):
        errorStr = f"Error type: {ErrorTypeStr[errorType]}\n\n{errorMsg}"
        ErrorMessage.__init__(self, errorStr, parent=parent)


class UrlDialog(QDialog):
    def __init__(self, url='', acceptTxt=_("Save"), parent=None):
        QDialog.__init__(self, parent=parent)

        layout = QFormLayout(self)

        label = QLabel("Scheme:")
        self._schemeSelect = QComboBox(self)
        self._schemeSelect.addItems(["http", "https"])
        layout.addRow(label, self._schemeSelect)

        label = QLabel("URL:")
        self._urlEdit = QLineEdit(self)
        layout.addRow(label, self._urlEdit)

        self._cancelButton = Button(_("Cancel"), self)
        self._saveButton = Button(acceptTxt, self)
        layout.addRow(self._cancelButton, self._saveButton)

        self._urlEdit.textEdited.connect(self.__inputChanged)
        self._saveButton.clicked.connect(self.accept)
        self._cancelButton.clicked.connect(self.reject)

        parsedUrl = urlparse(url)
        if parsedUrl.scheme == 'http':
            self._schemeSelect.setCurrentIndex(0)
        else:
            # Default to https
            self._schemeSelect.setCurrentIndex(1)

        self._urlEdit.setText(f"{parsedUrl.netloc}{parsedUrl.path}")

    def __inputChanged(self, text):
        newText = text.replace("https://", "").replace("http://", "")
        if text != newText:
            self._urlEdit.setText(newText)

        if self.isValid():
            self._saveButton.setEnabled(True)
        else:
            self._saveButton.setEnabled(False)

    def isValid(self):
        if urlparse(self.__currentUrl()).netloc:
            return True
        return False

    def __currentUrl(self):
        return f"{self._schemeSelect.currentText()}://{self._urlEdit.text()}"

    @property
    def url(self):
        if self.isValid():
            return self.__currentUrl()
        return ''
